package com.mxx.common.security;

import com.mxx.common.exception.EncryptionException;
import com.mxx.common.security.displacer.Displacer;
import com.mxx.common.utils.RandomUtil;

import javax.crypto.SecretKey;
import javax.crypto.spec.IvParameterSpec;
import java.nio.charset.StandardCharsets;
import java.security.SecureRandom;
import java.util.Base64;
import java.util.Optional;

/**
 * @author: mxx
 * @date: 2022/3/21
 * @time: 11:17
 * @Description: 描述信息
 */
public class KeyGenerator {

    private Displacer displacer;

    public KeyGenerator(Displacer displacer) {
        this.displacer = displacer;
    }

    public String getAesKey(Integer keySize) throws EncryptionException {
        try {
            if (keySize == null) {
                keySize = 0;
            }
            javax.crypto.KeyGenerator keyGenerator = javax.crypto.KeyGenerator.getInstance(Constant.CipherType.AES.name());
            keyGenerator.init(keySize);
            // 生成一个Key
            SecretKey generateKey = keyGenerator.generateKey();
            // 转变为字节数组
            byte[] encoded = generateKey.getEncoded();
            // 生成密钥字符串
            return displacer.encoderToString(encoded);
        } catch (Exception e) {
            throw new EncryptionException(e, "generate key exception");
        }
    }

    public String getKey() {

        try {
            javax.crypto.KeyGenerator keyGenerator = javax.crypto.KeyGenerator.getInstance(Constant.CipherType.DES.name());
            keyGenerator.init(56);
            // 生成一个Key
            SecretKey generateKey = keyGenerator.generateKey();
            // 转变为字节数组
            byte[] encoded = generateKey.getEncoded();
            // 生成密钥字符串
            return displacer.encoderToString(encoded);
        } catch (Exception e) {
            throw new EncryptionException(e, "generate key exception");
        }
    }


    public String getAesIV() {
        try {
            // 生产便偏移量，增加加密强度
            SecureRandom randomSecureRandom = SecureRandom.getInstance("SHA1PRNG");
            String str = RandomUtil.randomNumber(16).toLowerCase();
            byte[] ivByte = str.getBytes(StandardCharsets.UTF_8);
            randomSecureRandom.nextBytes(ivByte);
            IvParameterSpec ivParams = new IvParameterSpec(ivByte);
            return displacer.encoderToString(ivParams.getIV());
        } catch (Exception e) {
            throw new EncryptionException(e, "generate iv exception");
        }
    }

}
